package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:返回链表中间结点
 * User: 阿宾
 * Date: 2024-11-06
 * Time: 08:49
 */

public class Demo2 {
    //定义链表结点
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static ListNode solution(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            //注意判断条件，不能是fast.next != null && fast != null
            fast = fast.next.next;//快指针移动两步
            slow = slow.next;//慢指针移动一步
        }
        return slow;
    }

    public static void main(String[] args) {
        // 创建一个链表
        ListNode head = new ListNode(1, new ListNode(2));

        // 调用 solution 方法并输出结果
        ListNode middleNode = solution(head);
        System.out.println(middleNode.val);  // 输出中间节点的值
    }
}
